package com.example.com.skills_utf8;

import android.animation.ObjectAnimator;
import android.animation.TypeEvaluator;
import android.animation.ValueAnimator;
import android.app.Fragment;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.GestureDetectorCompat;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;

import com.app.util.Utils_Log;
import com.app.video.MyVideoCameraPreview;

import java.util.Timer;


//
public class _64_4Fragment2 extends Fragment {


    private final String TAG = _64_4Fragment2.class.getSimpleName();


    MyVideoCameraPreview preview;
    Timer timer = new Timer();

    Handler handler = new Handler();


    // 手势监听
    GestureDetectorCompat gesturedetector ;
    MyGestureListener gestureListener = new MyGestureListener();


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        final View view = inflater.inflate(R.layout.fragment_64_4, container, false);


        // 生成手势监听对象；
        gesturedetector = new GestureDetectorCompat(getActivity(), gestureListener);


        final FrameLayout layout_camera_content = (FrameLayout)view.findViewById(R.id.layout_camera_content);
        final ImageView iv = (ImageView) view.findViewById(R.id.iv_frame_box);

        preview = new MyVideoCameraPreview();
        final View iv_camera_content = (View)preview.init(getActivity());

        layout_camera_content.addView(iv_camera_content);

        preview.start();

        //
        iv_camera_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {


                float x = event.getX();  //相对于本身view的左上角的偏移值
                float y = event.getY();


                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    Utils_Log.e(TAG, "x: " + x + " y: " + y);
                    preview.SetAutoFoucs();


                    // 在屏幕绘制聚焦图案
                    int width = iv_camera_content.getWidth();
                    int height = iv_camera_content.getHeight();

                    int width_box = 256;
                    int height_box = 256;

                    // 本身就在屏幕坐标系下,无需转换
                    final int pos_x = (int) x; //width/2;
                    final int pos_y = (int) y; //height/2;

                    final int src_x = (int)width/2;
                    final int src_y = (int)height/2;


                    //
                    final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                    final Canvas canvas = new Canvas(bitmap);
                    final Paint paint = new Paint();
                    final Rect rect = new Rect();
                    rect.left = src_x - width_box / 2;
                    rect.top = src_y - height_box / 2;
                    rect.right = rect.left + width_box;
                    rect.bottom = rect.top + height_box;


                    paint.setColor(Color.BLUE);
                    paint.setStyle(Paint.Style.STROKE);
                    paint.setStrokeWidth(5);
                    canvas.drawRect(rect, paint);

                    final Paint paint_alpha = new Paint();
                    paint_alpha.setARGB(0, 0, 0, 0);
                    paint_alpha.setStyle(Paint.Style.STROKE);
                    paint_alpha.setStrokeWidth(5);

                    /*
                    Matrix matrix = new Matrix();
                    matrix.postTranslate(pos_x - src_x, pos_y - src_y);
                    RectF rect_dest = new RectF();
                    rect_dest.set(rect);
                    matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                    canvas.drawRect(rect_dest, paint);
                    */


                    // 缩放和平移没有成功搭配；
                    {


                        ValueAnimator valueAnimator = new ValueAnimator();
                        valueAnimator.setDuration(3000);
                        valueAnimator.setObjectValues(new Bean());
                        valueAnimator.setInterpolator(new LinearInterpolator());
                        valueAnimator.setEvaluator(new TypeEvaluator<Bean>() {
                            @Override
                            public Bean evaluate(float fraction, Bean startValue,
                                                 Bean endValue) {

                                Bean bean = new Bean();
                                PointF point1 = new PointF();
                                PointF point2 = new PointF();

                                float delta_x = pos_x - src_x;
                                float delta_y = pos_y - src_y;

                                bean.trans.x = delta_x*fraction;
                                bean.trans.y = delta_y*fraction;
                                bean.scale.x = (1-fraction); //fraction * 2;// //[0-1]
                                bean.scale.y = (1-fraction); //fraction * 2;//(1-fraction);


                                Log.e(TAG,  "-trans.x: "+ bean.trans.x + " trans.y: "+bean.trans.y);
                                Log.e(TAG,  "---scale.x: "+ bean.scale.x + " scale.y: "+bean.scale.y);


                                return bean;
                            }
                        });

                        valueAnimator.start();
                        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                            @Override
                            public void onAnimationUpdate(ValueAnimator animation) {
                                Bean bean = (Bean) animation.getAnimatedValue();

                                Matrix matrix = new Matrix();
                         //       matrix.postScale( bean.scale.x, bean.scale.y);
                                //matrix.setScale(bean.scale.x, bean.scale.y);
                                matrix.postTranslate( bean.trans.x, bean.trans.y);
                                RectF rect_dest = new RectF();
                                rect_dest.set(rect);   // 定位到源矩形位置
                                matrix.mapRect(rect_dest);  // 变换该矩形，使其在目标处显示
                                canvas.drawRect(rect_dest, paint);

                                iv.setImageBitmap(bitmap);

                            }
                        });


                        iv.setImageBitmap(bitmap);


                    }



                }


                return gesturedetector.onTouchEvent(event);
            }
        });




        preview.mycamera.printSupportFocusMode();
        preview.mycamera.printSupportFlashMode();
        preview.mycamera.printZoomRatios();;


        int MaxZoom = preview.mycamera.GetMaxZoom();
        SeekBar sb_zoom = (SeekBar)view.findViewById(R.id.sb_zoom);
        sb_zoom.setMax(MaxZoom);
        sb_zoom.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                preview.mycamera.SetZoom(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });


        //ProgressBar bar = new ProgressBar(getActivity());




        return view;

    }


    class Bean
    {
        PointF trans;
        PointF scale;

        public Bean(){
            trans = new PointF(0,0);
            scale = new PointF(1,1);
        }

    }




    @Override
    public void onPause() {
        super.onPause();
        //System.out.println("onPause");

        preview.close();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        //System.out.println("onDestroy");

        //preview.close();
    }



    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            Utils_Log.e(TAG, "onDoubleTap");

            // 使相机变焦，拉近
            if(preview.mycamera.GetZoom() == preview.mycamera.GetMaxZoom() ){

                new Thread(new Runnable() {

                    int progress = preview.mycamera.GetMaxZoom();

                    public void run() {
                        while (progress > 0) {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }

                            // Update the progress bar
                            handler.post(new Runnable() {
                                public void run() {
                                    preview.mycamera.SetZoom(progress--);
                                }
                            });
                        }
                    }
                }).start();

            }
            else{

                new Thread(new Runnable() {

                    int MaxZoom = preview.mycamera.GetMaxZoom();
                    int progress = 0;

                    public void run() {
                        while (progress < MaxZoom) {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e1) {
                                e1.printStackTrace();
                            }

                            // Update the progress bar
                            handler.post(new Runnable() {
                                public void run() {
                                    preview.mycamera.SetZoom(progress++);
                                }
                            });
                        }
                    }
                }).start();

            }




            return super.onDoubleTap(e);
        }


        @Override
        public boolean onDown(MotionEvent e) {
            Utils_Log.e(TAG, "onDown");
            return true;        // 返回true，使后续能接着处理
        }

    }





}
